package bsi.vn.FirstApp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.ATMData;
import bsi.vn.Data.ContractATMListAdapter;
import bsi.vn.Data.CookieData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class ContractATMListFragment extends Fragment implements OnScrollListener{
	private Activity context;
	private int CTID;
	private SimpleDateFormat format;
	private ArrayList<ATMData> list;
	private ListView lv;
	
	private ArrayList<ATMData> templist;
	private int a ;
	private int b ;
	private int flag;
	private int size = 50;
	private ContractATMListAdapter adapter;
	
	private View tab3;
	
	public ContractATMListFragment( int cTID , Context context) {
		super();
		this.context = (Activity) context;
		CTID = cTID;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		container.removeAllViews();
		
		if (tab3 != null) {
	        ViewGroup parent = (ViewGroup) tab3.getParent();
	        if (parent != null)
	            parent.removeView(tab3);
	    }
	    try {
	        tab3 = inflater.inflate(R.layout.fragment_contract_atmlist, container, false);
	    } catch (InflateException e) {
	        Log.d("test", "Inflate Exception");
	    }
		
		flag = 0;
		a  = 0;
		b = 0;
		templist = new ArrayList<ATMData>();
//		View tab3 = inflater.inflate(R.layout.fragment_contract_atmlist, container,false);
		format = new SimpleDateFormat("ddMMyyyyHHmm");
		lv = (ListView) tab3.findViewById(R.id.lvCATMList);
		list = new ArrayList<ATMData>();
//		TextView tvSNO = (TextView) tab3.findViewById(R.id.tktvTicketNo);
//		TextView tvCIT = (TextView) tab3.findViewById(R.id.tktvSerialNo);
//		TextView tvDEP = (TextView) tab3.findViewById(R.id.tktvAddress);
//		tvSNO.setText(R.string.CTATMListSno);
//		tvCIT.setText(R.string.CTATMListCit);
//		tvDEP.setText(R.string.CTATMListDep);
		myContractATMList mydata = new myContractATMList();
		mydata.execute(new String[] {CTID+""});
		lv.setOnScrollListener(this);
		return tab3;
	}
	
	
	private class myContractATMList extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetContractATMList(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
//			Log.d("test", result);
			String loc_arResponse[] = result.split("\\|");
			
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(context,
						LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(context,
						"Error", loc_arResponse[1]);
				return;
			}

			try {
				list.clear();
//				Log.d("test", loc_arResponse[1]);
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
				for (int i = 0; i < jArray.length(); i++) {
//					Log.d("test", i+"");
					JSONObject json_data = jArray.getJSONObject(i);
//					ContractDetailData coData = new ContractDetailData();
					ATMData atm = new ATMData();
//					Log.d("test", "lengh " + jArray.length());
					int aid = json_data.getInt(Consts.SDB_ATMID);
					String sno = json_data.getString(Consts.SDB_SERIALNO);
					String cit = json_data.getString(Consts.SDB_PROVINCE);
					String dep = json_data.getString(Consts.SDB_DEPARTURE);
					atm.setATMId(aid);
					atm.setSerialNo(sno);
					atm.setProvince(cit);
					
					if(dep.equals("")){
						atm.setDeploy(null);
					}else{
						Date date = format.parse(dep);
						atm.setDeploy(date);
						
					}
					list.add(atm);
					
					
//					coData.setContractId(json_data
//							.getInt(Consts.SDB_CONTRACTID));
//					coData.setContractNo(json_data
//							.getString(Consts.SDB_CONTRACTNO));
//					coData.setExpireDate(json_data
//							.getString(Consts.SDB_EXPIREDATE));
//					coData.setCustomer(json_data.getString(Consts.SDB_CUSTOMER));


				}
				if(list.size() > 50){
					for(int i = 0; i< 50;i++){
						templist.add(list.get(i));
					}
					adapter = new ContractATMListAdapter(context, R.layout.fragment_contract_atmlist_item, templist);
					
					lv.setAdapter(adapter);
					Log.d("test", templist.size()+"");
				}else{
					adapter = new ContractATMListAdapter(context, R.layout.fragment_contract_atmlist_item, list);
					lv.setAdapter(adapter);
					Log.d("test", list.size()+"");
				}
				
			} catch (JSONException e) {
				Log.e("test", "Error parsing data " + e.toString());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				Log.e("test", "Error parsing data " + e.toString());
			}

			

			// lvTicket.setOnItemClickListener(new OnItemClickListener() {
			// @Override
			// public void onItemClick(AdapterView<?> parent, View view,
			// int position, long id) {
			// int TicketId = ticketData.get(position).getTicketId();
			// Intent i = new Intent(getApplicationContext(),
			// TicketDetailActivity.class);
			// i.putExtra("TicketId", TicketId);
			// startActivity(i);
			// }
			// });
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}

	}
	
	private String GetContractATMList(String contractID) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc
					.GetCookie(context);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_CONTRACTATMLIST));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CONTRACTID, CTID +""));


			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		
		loadLimit(firstVisibleItem,visibleItemCount,totalItemCount);

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {

		
	}
	
	public void loadLimit(int firstVisibleItem, int visible, int totalcount){
		if(totalcount - visible == firstVisibleItem && firstVisibleItem > flag){
			flag +=  (totalcount - visible);
//			loadSize(50);
			a = templist.size();
			if((list.size() -a >= 50) ){
				b = a + size;
			}else{
				b = list.size();
			}
			
			Log.d("test", "a =  " + a);
			Log.d("test", "b =  " + b);
			Log.d("test", "active at " + firstVisibleItem);
			for(int i = a; i< b;i++){
				templist.add(list.get(i));
			}
			adapter.notifyDataSetChanged();
		}		
	}
	
}
